#include "tools.h"
class Solution {
public:
    void reverse(ListNode *left, ListNode *right){
        ListNode *pre = left, *cur = left->next, *nxt;
        while(pre != right){
            nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }
    }
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode headpre(-1, head);
        ListNode *p1pre = nullptr, *p1, *p2, *p2nxt, *p = &headpre;
        int i = 0;
        for(; i < left; ++i) {p1pre = p; p = p->next;}
        // cout << i << " " << p->val << endl;
        p1 = p;
        for(; i < right; ++i) p = p->next;
        // cout << i << " " << p->val << endl;
        p2 = p;
        p2nxt = p2->next;

        reverse(p1, p2);
        p1pre->next = p2;
        p1->next = p2nxt;

        return headpre.next;
    }   
};